package com.core.shared;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2017/11/28
 * Time: 13:48
 * To change this template use Editor | File and Code Templates.
 */
public class TraceUtil {

    public static final String TRACE_ID = "TraceId";  //每个请求都含有的id，用来标识一次唯一的请求

    /**
     * 为请求分配一个traceId
     *
     * @param request
     */
    public static String assignRequestTraceId(HttpServletRequest request) {
        String traceId = UUID.randomUUID().toString();
        request.setAttribute(TRACE_ID, traceId);
        return traceId;
    }

    /**
     * 获取一个请求的traceId
     *
     * @param request
     * @return
     */
    public static String getRequestTraceId(HttpServletRequest request) {
        return (String) request.getAttribute(TRACE_ID);
    }

    /**
     * 获取当前线程的request对应的traceId
     *
     * @return
     */
    public static String getCurrentRequestTraceId() {
        return getRequestTraceId(WebUtil.getRequest());
    }


}
